<?php

namespace Admin\Controller;

/**
 * 微信
 */
class WechatController extends CommonController{
    
    /**
     * 文本 关键词回复-列表
     */
    public function text_list(){
        $where['type'] = '1';
        if(I('get.keywords')) $where['keyword'] = array('like','%'.I('get.keywords').'%');
        $dataPage = $this->getPager(M('Common'),$where);
        $this->assign('list',$dataPage['data']);
        $this->assign('page',$dataPage['page']);
        $this->display();
    }
    /**
     * 单图文 关键词回复-列表
     */
    public function single_list(){
    	$where['type'] = '2';
    	if(I('get.keywords')) $where['keyword'] = array('like','%'.I('get.keywords').'%');
    	$dataPage = $this->getPager(M('Common'),$where);
    	$this->assign('list',$dataPage['data']);
    	$this->assign('page',$dataPage['page']);
    	$this->display();
    }
    
    /**
     * 图片 关键词回复-列表
     */
    public function image_list(){
        $where['type'] = '4';
        if(I('get.keywords')) $where['keyword'] = array('like','%'.I('get.keywords').'%');
        $dataPage = $this->getPager(M('Common'),$where);
        $this->assign('list',$dataPage['data']);
        $this->assign('page',$dataPage['page']);
        $this->display();
    }
    
    /**
     * 文本 关键词回复-保存
     */
    public function text_edit(){
        if(IS_POST){
            $postData = I('post.');
            $data = $postData['info'];
            //关键词过滤
            $data['keyword'] = trim(str_replace("，",",",$data['keyword']),',');
            $keywordArr = explode(',',$data['keyword']);
            $WxKeyword = M('Keyword');
            foreach($keywordArr as $v){
                $keywordRes = $WxKeyword->where(array('customer_id'=>$this->customer_id,'keyword'=>$v))->find();
                if(empty($data['id']) && $keywordRes){
                    $this->error("关键词 ".$v." 已存在，请更换");
                }elseif($data['id']){
                    if($kEditRes = $WxKeyword->where(array('customer_id'=>$this->customer_id,'common_id'=>array('neq',$data['id']),'keyword'=>$v))->find())
                        $this->error("关键词 ".$v." 已存在，请更换");
                }
            }
            if(empty($data['keyword'])) $this->error("请输入关键词");
            
            $res = $data['id'] ? M('Common')->save($data) : M('Common')->add($data);
            if($res === false){
                $this->error('保存失败');
            }else{
                //保存关键词
                $common_id = $data['id'] ? $data['id'] : $res;
                $this->saveKeywords($WxKeyword, $common_id, $data['keyword'], 'text');
                $this->success('保存成功');
            }
        }else{
            $item = array();
            if(I('get.id')) $item = M('Common')->find(I('get.id'));
            $this->assign('item',$item);
            $this->assign('upPageUrl',$_SERVER['HTTP_REFERER']);
            $this->display();
        }
    }
    /**
     * 单图文 关键词回复-保存
     */
    public function single_edit(){
        if(IS_POST){
            $postData = I('post.');
            $data = $postData['info'];
            //关键词过滤
            $data['keyword'] = trim(str_replace("，",",",$data['keyword']),',');
            $keywordArr = explode(',',$data['keyword']);
            $WxKeyword = M('Keyword');
            foreach($keywordArr as $v){
                $keywordRes = $WxKeyword->where(array('customer_id'=>$this->customer_id,'keyword'=>$v))->find();
                if(empty($data['id']) && $keywordRes){
                    $this->error("关键词 ".$v." 已存在，请更换");
                }elseif($data['id']){
                    if($kEditRes = $WxKeyword->where(array('customer_id'=>$this->customer_id,'common_id'=>array('neq',$data['id']),'keyword'=>$v))->find())
                        $this->error("关键词 ".$v." 已存在，请更换");
                }
            }
            if(empty($data['keyword'])) $this->error("请输入关键词");
            
            $res = $data['id'] ? M('Common')->save($data) : M('Common')->add($data);
            if($res === false){
                $this->error('保存失败');
            }else{
                //保存关键词
                $common_id = $data['id'] ? $data['id'] : $res;
                $this->saveKeywords($WxKeyword, $common_id, $data['keyword'], 'single');
                $this->success('保存成功');
            }
        }else{
            $item = array();
            if(I('get.id')) $item = M('Common')->find(I('get.id'));
            $this->assign('item',$item);
            $this->assign('upPageUrl',$_SERVER['HTTP_REFERER']);
            $this->display();
        }
    }
    /**
     * 图片 关键词回复-保存
     */
    public function image_edit(){
        if(IS_POST){
            $postData = I('post.');
            $data = $postData['info'];
            //关键词过滤
            $data['keyword'] = trim(str_replace("，",",",$data['keyword']),',');
            $keywordArr = explode(',',$data['keyword']);
            $WxKeyword = M('Keyword');
            foreach($keywordArr as $v){
                $keywordRes = $WxKeyword->where(array('customer_id'=>$this->customer_id,'keyword'=>$v))->find();
                if(empty($data['id']) && $keywordRes){
                    $this->error("关键词 ".$v." 已存在，请更换");
                }elseif($data['id']){
                    if($kEditRes = $WxKeyword->where(array('customer_id'=>$this->customer_id,'common_id'=>array('neq',$data['id']),'keyword'=>$v))->find())
                        $this->error("关键词 ".$v." 已存在，请更换");
                }
            }
            if(empty($data['keyword'])) $this->error("请输入关键词");
            
            $res = $data['id'] ? M('Common')->save($data) : M('Common')->add($data);
            if($res === false){
                $this->error('保存失败');
            }else{
                //保存关键词
                $common_id = $data['id'] ? $data['id'] : $res;
                $this->saveKeywords($WxKeyword, $common_id, $data['keyword'], 'image');
                $this->success('保存成功');
            }
        }else{
            $item = array();
            if(I('get.id')) $item = M('Common')->find(I('get.id'));
            $this->assign('item',$item);
            $this->assign('upPageUrl',$_SERVER['HTTP_REFERER']);
            $this->display();
        }
    }
    
    /**
     * 关键词回复-删除
     */
    public function commonDel($id){
        $id = (int)$id;
        if($res = M('Common')->delete($id)){
            M('Keyword')->where(array('common_id'=>$id))->delete();
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }
    
    /**
     * 自定义菜单
     */
    public function index_menu(){
        $list = M("Menu")->order("id desc")->select();
        foreach($list as $v){
            if($v['position'] == 1){
                $first[] = $v;
            }elseif($v['position'] == 2){
                $second[] = $v;
            }elseif($v['position'] == 3){
                $third[] = $v;
            }
        }
        $this->assign("first",$first);
        $this->assign("second",$second);
        $this->assign("third",$third);
        $this->display();
    }

    /**
     * 保存菜单
     */
    public function saveMenu(){
        $data = I();
        $menu = M('Menu')->where(array("position"=>I("position")))->find();
        if(empty($menu)){
            $data['pid'] = 0;
        }else{
            $data['pid'] = $menu['id'];
        }
        $data['customer_id'] = $this->customer_id;
        $res = I("id") ? M('Menu')->save($data) : M('Menu')->add($data);
        $res === false ? $this->error('保存失败') : $this->success('保存成功');
    }

    /*
     *编辑菜单
     */
    public function editMenu(){
        $item = M('Menu')->where(array("id"=>(int)I("id")))->find();
        $this->success($item);
    }

    /**
     * 删除菜单
     */
    public function deleteMenu(){
        $res = M('Menu')->delete((int)I("id"));
        $res == false ? $this->error('删除失败') : $this->success('删除成功');
    }

    /**
     * 生成菜单
     * @return string
     * "url" => "http://baixinxing.yunapply.com/wechat/",
     */
    public function createMenu() {
        $first = M('Menu')->where(array("position"=>1))->order("id desc")->select();
        if(count($first)>1){
            for($i=0;$i<count($first)-1;$i++){
                $keyName = $first[$i]['type'] == 'view' ? 'url' : 'key';
                $arr[] = array("type"=>$first[$i]['type'],"name"=>$first[$i]['title'],$keyName=>$first[$i]['url']);
            }
            $menu[0] = array("name"=>$first[count($first)-1]['title'],"sub_button"=>$arr);
        }elseif($first){
            $keyName = $first[0]['type'] == 'view' ? 'url' : 'key';
            $menu[0] = array("type"=>$first[0]['type'],"name"=>$first[0]['title'],$keyName=>$first[0]['url']);
        }

        $second = M('Menu')->where(array("position"=>2))->order("id desc")->select();
        if(count($second)>1){
            for($i=0;$i<count($second)-1;$i++){
                $keyName = $second[$i]['type'] == 'view' ? 'url' : 'key';
                $arr2[] = array("type"=>$second[$i]['type'],"name"=>$second[$i]['title'],$keyName=>$second[$i]['url']);
            }
            $menu[1] = array("name"=>$second[count($second)-1]['title'],"sub_button"=>$arr2);
        }elseif($second){
            $keyName = $second[0]['type'] == 'view' ? 'url' : 'key';
            $menu[1] = array("type"=>$second[0]['type'],"name"=>$second[0]['title'],$keyName=>$second[0]['url']);
        }

        $third = M('Menu')->where(array("position"=>3))->order("id desc")->select();
        if(count($third)>1){
            for($i=0;$i<count($third)-1;$i++){
                $keyName = $third[$i]['type'] == 'view' ? 'url' : 'key';
                $arr3[] = array("type"=>$third[$i]['type'],"name"=>$third[$i]['title'],$keyName=>$third[$i]['url']);
            }
            $menu[2] = array("name"=>$third[count($third)-1]['title'],"sub_button"=>$arr3);
        }elseif($third){
            $keyName = $third[0]['type'] == 'view' ? 'url' : 'key';
            $menu[2] = array("type"=>$third[0]['type'],"name"=>$third[0]['title'],$keyName=>$third[0]['url']);
        }
        $menu = array("button"=>$menu);
        
        //获取access_token
        $access_token = D('Customer')->getToken($this->customer_id);
        if(empty($access_token)) $this->error(D('Customer')->getError());
        //发布菜单
        if(empty($menu)) $this->error('未保存自定义菜单');

        $result = D('Api')->createMenu($access_token, $menu);
        if($result['errcode'] === 0){
            $this->success('发布成功');
        }else{
            $errText = D('Api')->getErrText($result['errcode']);
            if(empty($errText)) $errText = $result['errmsg'];
            $result['errcode'] > 0 ? $this->error($errText) : $this->error('发布失败');
        }
    }
    
    /**
     * 首次关注、无匹配回复
     */
    public function save_auto_reply(){
        if(IS_POST){
            $data = I('post.');
            $res = $data['info']['id'] ? M('AutoReply')->save($data['info']) : M('AutoReply')->add($data['info']);
            $res === false ? $this->error('保存失败') : $this->success('保存成功');
        }else{
            $this->assign('item', M('AutoReply')->where(array('type'=>I('get.type')))->find());
            $this->display();
        }
    }

    /**
     * url-token
     */
    public function url_token(){
        $this->assign('url','http://'.$_SERVER['HTTP_HOST'].U('Api/index'));
        $this->assign('token',C('TOKEN'));
        $this->display();
    }
    
    //粉丝列表
    public function member($keywords = ''){
        $where = array();
        if($keywords) $where['nickname'] = array('like','%'.$keywords.'%');
        $dataPage = $this->getPager(M('Member'),$where);
        $this->assign('list',$dataPage['data']);
        $this->assign('page',$dataPage['page']);
        $this->display();
    }
    
    /**
     * 数据列表及分页
     * @param mixed $where 查询条件
     * @param int $pageSize 页大小
     * @param string $order 排序
     * @return array array('data'=>数据列表,'page'=>分页)
     */
    private function getPager($model,$where=array(),$pageSize=10,$order='id desc'){
        I('get.p') ? $p=I('get.p') : $p=1;
        $list = $model->where($where)->order($order)->page($p.','.$pageSize)->select();
        $count = $model->where($where)->count();
        $Page = new \Think\Page($count,$pageSize);
        $show = $Page->show();
        return array(
            'data' => $list,
            'page' => $show,
        );
    }
    
    private function saveKeywords($model, $common_id, $keyword, $type = 'text'){
        $model->where(array('common_id'=>$common_id,'type'=>$type))->delete();
        $wordArr = explode(',',$keyword);
        foreach($wordArr as $word){
            $model->add(array('customer_id'=>$this->customer_id,'common_id'=>$common_id,'keyword'=>trim($word),'type'=>$type));
        }
    }
    
}
